/* Copyright (C) 2011 Riccardo Marson

   This file is part of OpenPool, an open-source game of pool.

   Permission is hereby granted, free of charge, to any person obtaining a
   copy of this software and associated documentation files (the "Software"),
   to deal in the Software without restriction, including without limitation
   the rights to use, copy, modify, merge, publish, distribute, sublicense,
   and/or sell copies of the Software, and to permit persons to whom the
   Software is furnished to do so, subject to the following conditions:

   The above copyright notice and this permission notice shall be included
   in all copies or substantial portions of the Software.

   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
   OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
   FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
   RICCARDO MARSON BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
   AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
   CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

  See Readme.rtf for further information.

*/

#include "application.h"

#include <iostream>
#include <sstream>


//------------------------------

CCoreApplication::CCoreApplicationListener::CCoreApplicationListener(string name, CCoreApplication *parent) :
    CBaseEventListener(name)
{
    mParent = parent;
}

CCoreApplication::CCoreApplicationListener::~CCoreApplicationListener()
{

}

bool CCoreApplication::CCoreApplicationListener::processEvent(EventPtr event)
{
    eEventType evT = event->getEventType();

    //each listeners is already registered only to events of interest,
    //there should be no need to check if the incoming event is valid.

    CKeyEvent *k_event = NULL;

    switch (evT)
    {
    case EV_KEY_PRESS:

        k_event = dynamic_cast<CKeyEvent*>(event.get());

        switch( k_event->key() )
        {
        case sf::Key::Escape:
            mParent->showMenu();
        break;
        default:
            break;
        }

        break;
    case EV_QUIT_APPLICATION:
        mParent->isRunning = false;
        break;
    default:
        return false;
        break;
    }

    return true;
}


CCoreApplication::CCoreApplication(const char *argv0, string listenerName)
{
    logManager = LogManagerPtr( new CLogManager(argv0) );

    //Open the log file for the current session
    logManager->setLogFile(mConfigOptions.logFileName.c_str());

    logManager->setDebugMode(mConfigOptions.logDebugModeActive);

    if (mConfigOptions.logDebugModeActive)
        logManager->logMessage("Log Debug Mode is Active.");

    logManager->logMessage("OpenPool Session Started.");

    //Fire up game subsystems
    resourceCache = ResCachePtr( new CResourceCache(argv0) );

    // register resources search paths
    string modelPath = "models";
    string texPath = "images";
    string soundPath = "sounds";
    string scriptPath = "scripts";

    resourceCache->registerSearchPath(modelPath);
    resourceCache->registerSearchPath(texPath);
    resourceCache->registerSearchPath(soundPath);
    resourceCache->registerSearchPath(scriptPath);

    //init scripting engine

    scriptManager = ScriptManagerPtr( new CScriptManager() );
    scriptManager->init();

    //gloabal variables must be set before compiling scripts
    scriptManager->registerGlobalProperty("CConfigOptions cnf", &mConfigOptions);

    scriptManager->configure();

    //Load Config Options
    scriptManager->executeFunction("Config", "void loadConfigOptions()");

    eventManager = EventManagerPtr( new CEventManager() );
    soundSystem = SoundSystemPtr( new CSoundSystem() );
    gameLogic = GameLogicPtr( new CLogic() );

    //create and register the MainWindow Event Listener
    mEventListener = EventListenerPtr( new CCoreApplicationListener(listenerName, this) );

    eventManager->registerListener(EV_KEY_PRESS, mEventListener);
    eventManager->registerListener(EV_QUIT_APPLICATION, mEventListener);

    //Initialize the Game Logic
    //Initialize this subsystem before the rendering engine.
    sceneBoundingRadius = 100.0f;

    gameLogic->InitPhysicsEngine(mConfigOptions.simTimeStep, mConfigOptions.gravity, mConfigOptions.frictionCoefficient, mConfigOptions.airDensity);

    //Initialize the Sound System
    soundSystem->loadSoundResources();

    //Create the Render Window

    renderWindow = RenderPtr( new CRenderWindow() );

    renderWindow->setDebugModeActive(mConfigOptions.physicsDebugModeOn);

    //Setup Initial World Configuration
    setupWorld();

    //Resize and Show the Render Window
    renderWindow->resize( mConfigOptions.windowWidth, mConfigOptions.windowHeight );

    logManager->logMessage("OpenGL Engine Successfully Initialized.");

    //Set switches
    soundSystem->startBackgroundMusic();

    if (mConfigOptions.playMusic)
        soundSystem->backgroundMusicOn();
    else
        soundSystem->backgroundMusicOff();

    if (mConfigOptions.castShadows)
        renderWindow->toggleShadows(true);
    else
        renderWindow->toggleShadows(false);

    isRunning = true;

    logManager->logMessage("Starting Game.");

}

CCoreApplication::~CCoreApplication()
{
    eventManager->unregisterListener(mEventListener);

    gameLogic.reset();
    soundSystem.reset();
    renderWindow.reset();
    eventManager.reset();
    scriptManager.reset();
    resourceCache.reset();
    logManager.reset();
}

void CCoreApplication::resumeGame()
{
    //TODO
}

void CCoreApplication::quitGame()
{
   //TODO
}

void CCoreApplication::playButtonClickedSound()
{
    soundSystem->playButtonClick();
}

void CCoreApplication::playTextAcceptedSound()
{
    soundSystem->playTextAccepted();
}

void CCoreApplication::setupWorld()
{
    //TODO: load from script
	CLevelLoader *loader = new CLevelLoader(this);

	loader->AddRef();

    // load game / level

    scriptManager->executeFunction("Level_8Ball", "void load(LevelLoader@ loader)", 1,
    		(void**)(&loader));

    //TODO move to script

    //Camera moved into scene, broadcast event
    EventPtr cm_event( new CCameraMovedEvent(CVector3(0.0, 6.0, -10.4)) );
    //since the main loop is not yet active and the local copy of the camera
    //position in the sound system must be initialised, send this event syncronously.
    eventManager->sendEvent(cm_event);

    //************************************************************
    EventPtr startGame( new CBaseEvent(EV_START_GAME_REQUESTED) );
    eventManager->sendEvent(startGame);
    //************************************************************

    loader->Release();
}

void CCoreApplication::mainLoop()
{
    mainUpdateTimer.Reset();
    graphicsUpdateTimer.Reset();

    float update1 = 1.0;
    float update2 = 1.0;

    while (isRunning)
    {
        if ( update1 > ( 1.0 / 60.0 ) )
        {
            mainUpdateTimer.Reset();

            //Update the game state:
            gameLogic->UpdateState();

            eventManager->processEventQueue();

            scriptManager->processQueuedFunctions();

            renderWindow->pollUIEvents();
        }

       if ( update2 > ( 1.0 / 30.0) )
       {
            graphicsUpdateTimer.Reset();

            //Update the graphics
            renderWindow->updateGraphics();
       }

        update1 = mainUpdateTimer.GetElapsedTime();
        update2 = graphicsUpdateTimer.GetElapsedTime();
    }
}


void CCoreApplication::showMenu()
{
    //TODO
}
